package com.allen.app.common.config.other;

import cn.dev33.satoken.exception.NotLoginException;
import com.allen.app.common.config.dingtalk.DingTalkHelper;
import com.allen.app.common.domain.R;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
*
* Description: 全局异常拦截处理
*
* @author Limiaojun
* @date 2019/11/26 9:59
**/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Resource
    private Environment environment;

    /**
     * 处理参数异常
     */
    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseBody
    public R<?> exceptionHandler(IllegalArgumentException e) {
        return R.error().setMessage(e.getMessage());
    }

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public R<?> exceptionHandler(BusinessException e) {
        if(e.isPrintLog()){
            log.error("GlobalExceptionHandler.exceptionHandler.exception:\t ",e);
        }
        DingTalkHelper.send(e);
        return R.error().setMessage(e.getMessage());
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R<?> exceptionHandler(Exception e) {
        log.error("",e);
        return R.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"服务器跑路了");
    }

    // 全局异常拦截（拦截项目中的NotLoginException异常）
    @ExceptionHandler(NotLoginException.class)
    @ResponseBody
    public R<?> handlerNotLoginException(NotLoginException nle) {

        // 打印堆栈，以供调试
//        nle.printStackTrace();

        // 判断场景值，定制化异常信息
        String message = "";
        switch (nle.getType()) {
            case NotLoginException.NOT_TOKEN:
                message = "未提供token";
                break;
            case NotLoginException.INVALID_TOKEN:
                message = "token无效";
                break;
            case NotLoginException.TOKEN_TIMEOUT:
                message = "token已过期";
                break;
            case NotLoginException.BE_REPLACED:
                message = "token已被顶下线";
                break;
            case NotLoginException.KICK_OUT:
                message = "token已被踢下线";
                break;
            default:
                message = "当前会话未登录";
                break;
        }

        // 返回给前端
        return R.error(HttpStatus.UNAUTHORIZED.value(),message);
    }
}